package org.jeecg.modules.quartz.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.service.NCWebService;
import org.jeecg.common.nc.vo.WSVO;
import org.jeecg.modules.quartz.entity.TbJobLog;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecg.modules.quartz.service.ITbJobLogService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.Map;

/**
 * NC组织+部门同步
 */
public class NCDeptSyncJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(NCDeptSyncJob.class);

    // 系统部门操作类
    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    IQuartzJobService jobService;

    @Autowired
    private ITbJobLogService tbJobLogService;

    @Value("${qixin.ncserver.uri}")
    private String NC_SERVER_URI;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        String lastTime = jobService.queryLastTime("ncdeptsyncjob");
        String currentTime = DateUtil.now();
        Boolean first = false;
        if (StrUtil.isBlank(lastTime)){
            lastTime = "2008-01-01 00:00:00";
            first = true; // 表示第一次同步
        }

        // 获取NC组织数据
        try {
            WSVO vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.DEPT,lastTime);
            for (Map<String, Object> map : vo.getContent()) {
                String pid = (String) map.get("pk_fatherorg");
                // 添加系统部门
                SysDepart sysDepart = new SysDepart();
                sysDepart.setOrgCategory("2");// 组织类型 -- 部门
                sysDepart.setCreateBy("admin");
                sysDepart.setUpdateBy("admin");
                sysDepart.setUpdateTime(new Date());
                sysDepart.setId((String) map.get("pk_dept"));
                sysDepart.setOrgCode((String) map.get("code"));
                sysDepart.setDepartName((String) map.get("name"));
                if (StrUtil.isBlank(pid)){
                    // 上级部门为空话，把上级部门设成组织
                    sysDepart.setParentId((String) map.get("pk_org"));
                }else{
                    sysDepart.setParentId((String) map.get("pk_fatherorg"));
                }
                sysDepart.setDelFlag( map.get("dr").toString());
                sysDepart.setPkGroup((String) map.get("pk_group"));
                sysDepartService.saveOrUpdate(sysDepart);

 /*               NcOrg ncOrg = new NcOrg();
                ncOrg.setSid((String) map.get("pk_dept"));
                ncOrg.setCode((String) map.get("code"));
                ncOrg.setPkFatherorg(pid);
                ncOrg.setName((String) map.get("name"));
                ncOrg.setPkGroup((String) map.get("pk_group"));
                ncOrg.setDr(map.get("dr").toString());
                orgService.saveOrUpdate(ncOrg);*/

            }
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("本次新增或更新记录" + vo.getContent().size() + "条");
            tbJobLog.setNum(vo.getContent().size());
            tbJobLogService.save(tbJobLog);
            if(first){
                // 新增一条记录
                jobService.insetLastTime("ncdeptsyncjob", currentTime);
            }else{
                //更新最后同步时间
                jobService.updateLastTime("ncdeptsyncjob", currentTime);
            }
            logger.info("NC组织同步成功更新：{}条", vo.getContent().size());
        } catch (Exception e) {
            logger.info("NC组织同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }

    }
}
